<?php

/**
 * Created by Reliese Model.
 */

namespace App\Models;

use App\Engine\BaseModel;
use Illuminate\Support\Facades\DB;
use App\Exceptions\ApiException;


/**
 * Class Sys
 *
 * @property int $id
 * @property string|null $key
 * @property string|null $value
 * @property int $type
 * @property int $switch
 * @property string|null $content
 * @property string|null $other
 *
 * @package App\Models
 */
class Sys extends BaseModel
{
	protected $table = 'sys';
	public $timestamps = false;

	protected $casts = [
		'type' => 'int',
		'switch' => 'int'
	];

	protected $fillable = [
		'key',
		'value',
		'type',
		'switch',
		'content',
		'other'
	];

    public $rule=[
        'key'=>'required',
        'type'=>'required',

    ];
    public $ruleMessage=[
        'key.required'=>"请输入键",
        'type.required'=>"请选择类型",
    ];

    public static function update_data($data)
    {
        DB::beginTransaction();
        try {
            $model=(new self());
            foreach ($data as $k=>$v){
                $model->where(['id'=>$v['id']])->update(['value'=>$v['value']]);
            }
            DB::commit();
            return ['data'=>true];
        }catch (\Exception $e){
            DB::rollback();
            throw new ApiException($e->getMessage());
        }
    }

    public static function getValue($key)
    {
        return self::where('key',$key)->value('value');
    }

    public function get_Value($key)
    {
        return $this->where("key",$key)->value("value");
    }


    public function getOtherAttribute($value)
    {
        if($value!=null)
            return explode(";",$value);
        return $value;
    }

    public static function get_sys_type($type)
    {
        $res=self::where("type",$type)->get();
        $arr=array();
        foreach ($res as $key=>$value)
            $arr[$value["key"]]=$value["value"];
        return $arr;
    }

}
